package jmine.tec.script.persistent.diagnostician;

import java.util.List;

import jmine.tec.script.ScriptExecutorException;
import jmine.tec.script.persistent.ScriptController;
import jmine.tec.script.persistent.dao.ScriptDAO;
import jmine.tec.script.persistent.domain.Script;
import bancosys.tec.persist.dao.BeanNotFoundException;
import bancosys.tec.rtm.diagnostician.AbstractDiagnostician;
import bancosys.tec.rtm.diagnostician.DiagnosisBean;

/**
 * Diagnosticador via Script.
 *
 * @author Marcio Ribeiro (mmr)
 * @created Dec 17, 2010
 */
public class ScriptDiagnostician extends AbstractDiagnostician {

    private ScriptController controller;

    private String scriptName;

    private String description;

    /**
     * Construtor.
     * 
     * @param controller controlador do componente script.
     * @param description descricao do que o script faz.
     * @param scriptName a ser executado.
     */
    public ScriptDiagnostician(ScriptController controller, String scriptName, String description) {
        this.controller = controller;
        this.scriptName = scriptName;
        this.description = description;
    }

    /**
     * {@inheritDoc}
     */
    public String getName() {
        return description;
    }

    /**
     * @return o script.
     */
    private Script getScript() {
        ScriptDAO dao = controller.getDAOFactory().getDAOByClass(ScriptDAO.class);
        try {
            return dao.findByNaturalKey(scriptName);
        } catch (BeanNotFoundException e) {
            throw new IllegalStateException(e);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected boolean fillDiagnosisBean(DiagnosisBean bean) {
        List<String> ds;
        try {
            ds = this.getScript().createContext(ScriptDiagnosticianContext.class).dispatchExecution();
        } catch (ScriptExecutorException e) {
            throw new IllegalStateException(e);
        }
        for (String d : ds) {
            bean.addDescription(d);
        }
        return true;
    }

}
